<?php

/**
 *    收银台控制器，其扮演的是收银员的角色，你只需要将你的订单交给收银员，收银员按订单来收银，她专注于这个过程
 *
 *    @author    Garbin
 */
class CashierApp extends ShoppingbaseApp {
    var $all_payments;
    
    function __construct() {
        $this->CashierApp();
    }

    function CashierApp() {
        parent::__construct();
        $this->all_payments = array('online' => array());  
    }
    /**
     *    根据提供的订单信息进行支付
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function index() {
        /* 外部提供订单号 */
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $order_id_array=explode(",", isset($_GET['order_id_array']) ? trim($_GET['order_id_array']) : '');

        if (!($order_id || !empty($order_id_array))) {
            $this->show_warning('no_such_order');
            return;
        }
        /* 内部根据订单号收银,获取收多少钱，使用哪个支付接口 */
        $order_model = & m('order');

$payment_model = & m('payment');
$payment_id=0;
$member_info = &m('member')->get($this->visitor->get('user_id'));
        if(isset($_GET['order_id_array'])){
    
            $order_info['order_id']='';
            $use_pd=0;
            $member_money=$member_info['money'];
            foreach($order_id_array as $order_id){
                $order_info0 = $order_model->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
                if (empty($order_info0)) {
                    $this->show_warning('no_such_order');

                    return;
                }
                /* 订单有效性判断 */
                if ($order_info0['payment_code'] != 'cod' && $order_info0['status'] != ORDER_PENDING) {
                    $this->show_warning('no_such_order');
                    return;
                }
                if($order_info['order_id']==''){
                    $order_info['order_id'].=$order_info0['order_id'];
                }else{
                    $order_info['order_id'].=','.$order_info0['order_id'];
                }
                
                
                $order_info['order_amount']=bcadd($order_info['order_amount'],$order_info0['order_amount'],2);
                $order_info['order_sn'].=($order_info['order_sn']?'、':'').$order_info0['order_sn'];
                $payment_id=$order_info0['payment_id'];
                
        /* 使用余额支付 当用户选择部分预付款支付时 */
        
        if ($order_info0['pd_amount'] != '0.00') {
            if ($member_money >= $order_info0['order_amount']) {
                $use_pd++;
                $member_money=bcsub($member_money,$order_info0['order_amount'],2);
                //有足够的余额，直接进行支付
                $order_model->edit($order_id, array('pd_amount' => $order_info0['order_amount']));
            } else {
                //没有足够的余额，则把预付款支付设置为余额设置为最大值
                $order_model->edit($order_id, array('pd_amount' => $member_money));
                $order_info0['pd_amount']=$member_money;
                $member_money=0;
            }
        }
            }
            if($use_pd==count($order_id_array)){
                header('Location:index.php?app=account_log&act=payment&order_id=' . $_GET['order_id_array']);
                exit;
            }
         /* 临时支付方式ID组 */
        $this->all_payments = array('online' => array());  
            /* 读取已安装的支付方式 */
            $payments      = $payment_model->get_builtin();
            $white_list    = $payment_model->get_white_list();
            $foreach_payment_id=0;
            foreach ($payments as $key => $payment)
            {
                if(in_array($key, $white_list)){
  
                        if ($payment['is_online']) {
                            
                                if ($payment['is_mobile'] != 1) {
                                    $payment['payment_code']=$payment['code'];
                                    $payment['payment_desc']=$payment['desc'];
                                    $payment['payment_name']=$payment['name'];
                                    $payment['payment_id']=++$foreach_payment_id;
                                    $this->all_payments['online'][] = $payment;
                                }
                         
                        } 
                  
                }
               
            }
        }else{    
        $order_info = $order_model->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
        if (empty($order_info)) {
            $this->show_warning('no_such_order');

            return;
        }
        /* 订单有效性判断 */
        if ($order_info['payment_code'] != 'cod' && $order_info['status'] != ORDER_PENDING) {
            $this->show_warning('no_such_order');
            return;
        }
        /* 使用余额支付 当用户选择部分预付款支付时 */
        
        if ($order_info['pd_amount'] != '0.00') {
            if ($member_info['money'] >= $order_info['order_amount']) {
                //有足够的余额，直接进行支付
                $order_model->edit($order_id, array('pd_amount' => $order_info['order_amount']));
                header('Location:index.php?app=account_log&act=payment&order_id=' . $order_id);
                exit;
            } else {
                //没有足够的余额，则把预付款支付设置为余额设置为最大值
                $order_model->edit($order_id, array('pd_amount' => $member_info['money']));
                $order_info['pd_amount']=$member_info['money'];
            }
        }
        }
        
if (!($payment_id || $order_info['payment_id']) || $_GET['batch']){

        if (!$order_info['payment_id'] && isset($_GET['order_id'])) {
            /* 若还没有选择支付方式，则让其选择支付方式 */
            $payments = $payment_model->get_enabled($order_info['seller_id']);
            


            /* 找出配送方式，判断是否可以使用货到付款 */
            $model_extm = & m('orderextm');
            $consignee_info = $model_extm->get($order_id);
            if (!empty($consignee_info)) {
                /* 需要配送方式 */
                $model_shipping = & m('shipping');
                $shipping_info = $model_shipping->get($consignee_info['shipping_id']);
                $cod_regions = unserialize($shipping_info['cod_regions']);
                $cod_usable = true; //默认可用
                if (is_array($cod_regions) && !empty($cod_regions)) {
                    /* 取得支持货到付款地区的所有下级地区 */
                    $all_regions = array();
                    $model_region = & m('region');
                    foreach ($cod_regions as $region_id => $region_name) {
                        $all_regions = array_merge($all_regions, $model_region->get_descendant($region_id));
                    }

                    /* 查看订单中指定的地区是否在可货到付款的地区列表中，如果不在，则不显示货到付款的付款方式 */
                    if (!in_array($consignee_info['region_id'], $all_regions)) {
                        $cod_usable = false;
                    }
                } else {
                    $cod_usable = false;
                }
                if (!$cod_usable) {
                    /* 从列表中去除货到付款的方式 */
                    foreach ($payments as $_id => $_info) {
                        if ($_info['payment_code'] == 'cod') {
                            /* 如果安装并启用了货到付款，则将其从可选列表中去除 */
                            unset($payments[$_id]);
                        }
                    }
                }
            }
            $this->all_payments = array('online' => array(), 'offline' => array());
            foreach ($payments as $key => $payment) {
                if ($payment['is_online']) {
//                    $this->all_payments['online'][] = $payment;
                    /*if ($payment['is_mobile'] != 1) {
                        $this->all_payments['online'][] = $payment;
                    }*/
                } else {
                    $this->all_payments['offline'][] = $payment;
                }
            }
            $payments      = $payment_model->get_builtin();
            $white_list    = $payment_model->get_white_list();
            $foreach_payment_id=0;
            foreach ($payments as $key => $payment)
            {
                if(in_array($key, $white_list)){
  
                        if ($payment['is_online']) {
                            
                                if ($payment['is_mobile'] != 1) {
                                    $payment['payment_code']=$payment['code'];
                                    $payment['payment_desc']=$payment['desc'];
                                    $payment['payment_name']=$payment['name'];
                                    $payment['payment_id']=++$foreach_payment_id;
                                    $this->all_payments['online'][] = $payment;
                                }
                         
                        } 
                  
                }
               
            }
            }
            $this->assign('order', $order_info);
            $this->assign('payments', $this->all_payments);
            $this->_curlocal(
                    LANG::get('cashier')
            );

            $this->_config_seo('title', Lang::get('confirm_payment') . ' - ' . Conf::get('site_title'));
			$this->assign('member_info', $member_info);
            		$this->display('cashier.payment.html');
        } else {
            if ($order_info['payment_id']){
            /* 否则直接到网关支付 */
			if(in_array($order_info['payment_code'],array('post','bank','cod','epayalipayrefund'))){
				/* 验证支付方式是否可用，若不在白名单中，则不允许使用 */
				if (!$payment_model->in_white_list($order_info['payment_code'])) {
					$this->show_warning('payment_disabled_by_system');
					return;
				}

				$payment_info = $payment_model->get("payment_code = '{$order_info['payment_code']}' AND store_id={$order_info['seller_id']}");

				/* 若卖家没有启用，则不允许使用 */
				if (!$payment_info['enabled']) {
					$this->show_warning('payment_disabled');
					return;
				}
			}else{
				$payment_info=$payment_model->get_builtin_info($order_info['payment_code']);
				$payment_info['payment_code']=$payment_info['code'];
                $payment_info['payment_desc']=$payment_info['desc'];
                $payment_info['payment_name']=$payment_info['name'];
				$payment_info['config']=serialize($payment_info['config']);
			}
			
            /* 生成支付URL或表单 */
            $payment = $this->_get_payment($order_info['payment_code'], $payment_info);
            try{
            	
            $payment_form = $payment->get_payform($order_info);
            
			}catch(WxPayException $e){
				$query_string=explode('&',$_SERVER['QUERY_STRING']);
				foreach($query_string as $key => $val){
					if($val=='code='.$_GET['code'] || $val=='state='.$_GET['state']){
						unset($query_string[$key]);
					}
				}

				$this->show_warning($e->getMessage(),'go_back',"index.php?".implode("&",$query_string));
				return;
			}
            if(!$payment_form){
            $this->show_warning("订单失效，请取消订单");

            return;
            }
            /* 货到付款，则显示提示页面 */
            if ($payment_info['payment_code'] == 'cod') {
                $this->show_message('cod_order_notice', 'view_order', 'index.php?app=buyer_order', 'close_window', 'javascript:window.close();');
                return;
            }

            /* 跳转到真实收银台 */
            $this->_config_seo('title', Lang::get('cashier'));
            $this->assign('payform', $payment_form);
            $this->assign('payment', $payment_info);
            $this->assign('order', $order_info);
            header('Content-Type:text/html;charset=' . CHARSET);
            /* 线下付款的 */
            if (!$payment_info['is_online']) {
                $this->_curlocal(Lang::get('post_pay_message'));
                $this->display('cashier.payform.html'); #线下付款调用的模板
            } else {
                $this->display('cashier.online.html'); #线上付款调用的模板
            }
        }
        if($payment_id){
            $order_info = $order_model->get("order_id=".reset($order_id_array)." AND buyer_id=" . $this->visitor->get('user_id'));
            /* 验证支付方式是否可用，若不在白名单中，则不允许使用 */
            if (!$payment_model->in_white_list($order_info['payment_code'])) {
                $this->show_warning('payment_disabled_by_system');
                return;
            }

            /* 生成支付URL或表单 */
            $payment_info=array();
            $payment_info['payment_id']=$order_info['payment_id'];
            $payment_info['store_id']=0;//站内线上支付
            $payment_info['payment_code']=$order_info['payment_code'];
            $payment_info['payment_name']=$order_info['payment_name'];
            $payment_info['payment_desc']='';
            $payment_info['config']='';
            $payment_info['enabled']=1;
            $payment_info['is_online']=1;
            $payment_info['sort_order']=0;
            foreach($this->all_payments as $fe_payment){
                if($fe_payment['payment_code']==$order_info['payment_code']){
                    $payment_info['is_mobile']=$fe_payment['is_mobile'];
                    break;
                }
            }
            $payment = $this->_get_payment($order_info['payment_code'], $payment_info);
            $order_info_array=array();
            $order_info_array['is_order_array']=1;
            $order_info_array['item']=array();
            foreach($order_id_array as $order_id){
                $order_info_array['item'][$order_id] = $order_model->get("order_id=".$order_id." AND buyer_id=" . $this->visitor->get('user_id'));
            }
            try{
            $payment_form = $payment->get_payform($order_info_array);
			}catch(WxPayException $e){
				$query_string=explode('&',$_SERVER['QUERY_STRING']);
				foreach($query_string as $key => $val){
					if($val=='code='.$_GET['code'] || $val=='state='.$_GET['state']){
						unset($query_string[$key]);
					}
				}

				$this->show_warning($e->getMessage(),'go_back',"index.php?".implode("&",$query_string));
				return;
			}
            /* 跳转到真实收银台 */
            $this->_config_seo('title', Lang::get('cashier'));
            $this->assign('payform', $payment_form);
            $this->assign('payment', $payment_info);
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->display('cashier.online.html');#线上付款调用的模板
            }
        }
    }
    
 
    /**
     *    确认支付
     *
     *    @author    Garbin
     *    @return    void
     */
    function goto_pay() {
        if(isset($_GET['order_id'])){
            $order_id_array=  explode(',', $_GET['order_id']);
            if(count($order_id_array)==1){
                $order_id=reset($order_id_array);
            }
        }
        $payment_id = isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0;
        if (!($order_id || !empty($order_id_array))) {
            $this->show_warning('no_such_order');

            return;
        }
        $order_model = & m('order');
        if($order_id){
        $order_info = $order_model->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
        if (empty($order_info)) {
            $this->show_warning('no_such_order');

            return;
        }
        }else{
            foreach($order_id_array as $order_id){
                $order_info = $order_model->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
                if (empty($order_info)) {
                    $this->show_warning('no_such_order');

                    return;
                }
            }
            
        }
        /* 使用余额支付 */
        if (!$payment_id) {
            if(count($order_id_array)==1){
            header('Location:index.php?app=account_log&act=payment&order_id=' . $order_id);
                exit;
            }else{

                header('Location:index.php?app=account_log&act=payment&order_id=' . $_GET['order_id']);
                exit;
            } 
        }

if(count($order_id_array)==1){
        if(in_array($_POST['payment_code'],array('post','bank','cod','epayalipayrefund'))){
			/* 验证支付方式 */
			$payment_model = & m('payment');
			$payment_info = $payment_model->get($payment_id);
            if (!$payment_info) {
				$this->show_warning('no_such_payment');

				return;
			}

			/* 保存支付方式 */
			$edit_data = array(
				'payment_id' => $payment_info['payment_id'],
				'payment_code' => $payment_info['payment_code'],
				'payment_name' => $payment_info['payment_name'],
			);

			/* 如果是货到付款，则改变订单状态 */
			if ($payment_info['payment_code'] == 'cod') {
				$edit_data['status'] = ORDER_SUBMITTED;
			}
		}else{
            $edit_data = array(
                'payment_id' => $payment_id,
                'payment_code' => $_POST['payment_code'],
                'payment_name' => $_POST['payment_name'],
            );
		}

        $order_model->edit($order_id, $edit_data);
			/* 如果是货到付款，则跳到订单列表 */
			if($edit_data['status'] == ORDER_SUBMITTED){
				header('Location:index.php?app=buyer_order');
                exit;
			}
        /* 开始支付 */
    $this->_goto_pay($order_id);
        }else{

            /* 保存支付方式 */
            $edit_data = array(
                'payment_id' => $payment_id,
                'payment_code' => $_POST['payment_code'],
                'payment_name' => $_POST['payment_name'],
            );
            foreach($order_id_array as $order_id){
                $order_model->edit($order_id, $edit_data);
            }
            $this->_goto_pay($_GET['order_id']);
        }
    }

    /**
     *    线下支付消息
     *
     *    @author    Garbin
     *    @return    void
     */
    function offline_pay() {
        if (!IS_POST) {
            return;
        }
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $pay_message = isset($_POST['pay_message']) ? trim($_POST['pay_message']) : '';
        if (!$order_id) {
            $this->show_warning('no_such_order');
            return;
        }
        if (!$pay_message) {
            $this->show_warning('no_pay_message');

            return;
        }
        $order_model = & m('order');
        $order_info = $order_model->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
        if (empty($order_info)) {
            $this->show_warning('no_such_order');

            return;
        }
        $edit_data = array(
            'pay_message' => $pay_message
        );

        $order_model->edit($order_id, $edit_data);

        /* 线下支付完成并留下pay_message,发送给卖家付款完成提示邮件 */
        $model_member = & m('member');
        $seller_info = $model_member->get($order_info['seller_id']);
        $mail = get_mail('toseller_offline_pay_notify', array('order' => $order_info, 'pay_message' => $pay_message));
        $this->_mailto($seller_info['email'], addslashes($mail['subject']), addslashes($mail['message']));

        $this->show_message('pay_message_successed', 'view_order', 'index.php?app=buyer_order', 'close_window', 'javascript:window.close();');
    }

    function _goto_pay($order_id) {
        $order_id_array=  explode(',', $order_id);
            if(count($order_id_array)==1){
                header('Location:index.php?app=cashier&order_id=' . reset($order_id_array));
            }else{
                header('Location:index.php?app=cashier&order_id_array=' . $order_id);
                    }
    }

}

?>
